package com.by.yz.loginUtil;

import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.by.yz.App;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.net.CookieStore;
import java.net.HttpCookie;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by pengpeng on 2017/3/18.
 */
public class HospitalRESTFul {
    public interface MyGETCallBack{
        public void ok(JSONArray response) throws JSONException;
        public void error(String response);
    }
    public interface MyPOSTCallBack{
        public void ok(JSONObject response) throws JSONException;
        public void error(String response);
    }

    public void getAllHospitals(final MyGETCallBack cb){
        String url=Constants.server_url+"/api/hospitals";
        JsonArrayRequest getRequest=new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                try {
                    cb.ok(response);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        },
                new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        error.printStackTrace();
                        cb.error(error.toString());
                    }
                }){

            @Override
            public Map<String, String> getHeaders() throws AuthFailureError {
                HashMap<String,String> headers=new HashMap<String,String>();
                CookieStore cookieJar= App.cookieManager.getCookieStore();
                List<HttpCookie> cookies=cookieJar.getCookies();
                for (HttpCookie cookie:cookies){
                    if(cookie.toString().contains("XSRF-TOKE")){
                        Log.e("token-post",cookie.getValue());
                        headers.put("X-XSRF-TOKEN",cookie.getValue());
                    }
                }
                return headers;
            }
        };
        App.requestQueue.add(getRequest);
    }

}
